package com.woniu.gateway.filters;

import com.woniu.gateway.service.IAuthService;
import com.woniu.gateway.util.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ：lgy
 * @description：全局认证过滤器
 * @date ：2022/11/12 10:19
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private IAuthService authService;
    private static Logger logger = LoggerFactory.getLogger(AuthGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getURI().toString();
        logger.info("进入网关:{}", uri);
        if (uri.endsWith("/users/login") || uri.endsWith("/v2/api-docs")) {
            logger.info("访问的是认证端点", uri);
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            logger.info("没有携带token，拒绝访问");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            ResultVO resultVO = ResultVO.failure("认证失败");
            return exchange.getResponse().setComplete();
        }
        logger.info("请求中携带token,开始校验token");
        ResultVO resultVO = authService.check(token);
        if (resultVO.getCode() == 500) {
            logger.info("校验失败，拒绝放行");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        logger.info("token校验通过，开始放行");

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
